
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  sms;

import dbmanager.DBManager;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.sql.ResultSet;
import java.util.*;

import logger.PoolLogger;

public class ReceiveThread extends Thread
{	
	private Hashtable<Object, Object> messageDetails = new Hashtable<Object, Object>();
	RecieveSMS recieve;
	SendSMS send ;
	PortHandler handle;
	PoolLogger pl;
	
	public ReceiveThread()
	{
		recieve = new RecieveSMS();
		handle = recieve.getPortHandler();
		send = new SendSMS(handle);
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	public void run()
    {
		while (true) 
		{
			try 
			{
				synchronized (this)
				{
					recieve.recieveSMS();
					send.sendSMS();	
				}
				{
					try 
					{
						System.out.println("mobile::ReceiveThread::run()::I'm in rec thread");
						pl.info("mobile::ReceiveThread::run()::I'm in rec thread");
						pl.debug("mobile::ReceiveThread::run()::I'm in rec thread");
						pl.warn("mobile::ReceiveThread::run()::I'm in rec thread");
						pl.fatal("mobile::ReceiveThread::run()::I'm in rec thread");
						pl.error("mobile::ReceiveThread::run()::I'm in rec thread");
						pl.trace("mobile::ReceiveThread::run()::I'm in rec thread");
						
						ResultSet rs = DBManager
								.getSelect("SELECT * FROM sms where send = 0 and status =0");
						while (rs.next()) {
							boolean FLAG = true;
							String multiple = rs.getString("multiple");
							String datetime = rs.getString("datetime");
							String username1 = rs.getString("mobile");
							String MsgText = rs.getString("message");
							String id = rs.getString("id");
							if (multiple.equals("1")) {
								FLAG = false;
								ResultSet rs1 = DBManager
										.getSelect("SELECT * FROM sms where send = 0 and status =0 and datetime = '"
												+ datetime
												+ "' and mobile = '"
												+ username1
												+ "' and id>"
												+ id
												+ " order by id");
								while (rs1.next()) {
									id = id + "," + rs1.getString("id");
									MsgText = MsgText
											+ rs1.getString("message");
									MsgText = MsgText.substring(0, MsgText
											.length() - 1);
									rs1.updateString("status", "1");
								}
								if (id.contains(",")) {
									FLAG = true;
								} else {
									rs1 = DBManager
											.getSelect("SELECT * FROM sms where send = 0 and status =0 and datetime > '"
													+ datetime
													+ "' and mobile = '"
													+ username1
													+ "' order by id");
									if (rs1.next()) {
										FLAG = true;
									}
								}
							}

							if (FLAG) {
								System.out.println("Username : " + username1);
								pl.info("Username : " + username1);
								pl.debug("Username : " + username1);
								pl.warn("Username : " + username1);
								pl.fatal("Username : " + username1);
								pl.error("Username : " + username1);
								pl.trace("Username : " + username1);
								System.out.println("MessageText : " + MsgText);
								pl.info("MessageText : " + MsgText);
								pl.debug("MessageText : " + MsgText);
								pl.warn("MessageText : " + MsgText);
								pl.fatal("MessageText : " + MsgText);
								pl.error("MessageText : " + MsgText);
								pl.trace("MessageText : " + MsgText);
								
								messageDetails.put("Username", username1);
								messageDetails.put("MessageText", MsgText);
								new ClientThread(messageDetails);
								//rs.updateString("status", "1");
								DBManager
										.getUpdate("update sms set status = 1 where id in( "
												+ id + ")");
							}

						}
						rs.close();
					} catch (Exception e) {
						System.out.println("mobile::ReceiveThread::run()::Server is in waiting state");
						pl.info("mobile::ReceiveThread::run()::Server is in waiting state");
						pl.debug("mobile::ReceiveThread::run()::Server is in waiting state");
						pl.warn("mobile::ReceiveThread::run()::Server is in waiting state");
						pl.fatal("mobile::ReceiveThread::run()::Server is in waiting state");
						pl.error("mobile::ReceiveThread::run()::Server is in waiting state");
						pl.trace("mobile::ReceiveThread::run()::Server is in waiting state");
						e.printStackTrace();
						pl.info(e.getMessage());
						pl.debug(e.getMessage());
						pl.warn(e.getMessage());
						pl.fatal(e.getMessage());
						pl.error(e.getMessage());
						pl.trace(e.getMessage());
					}
				}
				this.sleep(2000);

			} catch (Exception e) {
				System.out.println("mobile::ReceiveThread::run()::!!!!!!!! Exception \n");
				pl.info("mobile::ReceiveThread::run()::!!!!!!!! Exception \n");
				pl.debug("mobile::ReceiveThread::run()::!!!!!!!! Exception \n");
				pl.warn("mobile::ReceiveThread::run()::!!!!!!!! Exception \n");
				pl.fatal("mobile::ReceiveThread::run()::!!!!!!!! Exception \n");
				pl.error("mobile::ReceiveThread::run()::!!!!!!!! Exception \n");
				pl.trace("mobile::ReceiveThread::run()::!!!!!!!! Exception \n");
				e.printStackTrace();
				pl.info(e.getMessage());
				pl.debug(e.getMessage());
				pl.warn(e.getMessage());
				pl.fatal(e.getMessage());
				pl.error(e.getMessage());
				pl.trace(e.getMessage());
			}
		}
	}
	public static void main(String[] args) 
	{
		ReceiveThread rt = new ReceiveThread();

		rt.start();
		Timer time = new Timer();
		//time.schedule(rt, 0,2000);
		

	}
	
 }


class ClientThread extends Thread
{

//	Connection Data
 	private BufferedReader inputPort;
	private PrintStream outputport;
	private String Username, Request;
	PoolLogger pl;
	
	ClientThread(Hashtable<Object, Object> Message)
	{
		Username = Message.get("Username").toString();
		Request = Message.get("MessageText").toString();
		start();
		
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	public void run()
	{
		System.out.println("mobile::ClientThread::run()::I'm in receive thread");
		pl.info("mobile::ClientThread::run()::I'm in receive thread");
		pl.debug("mobile::ClientThread::run()::I'm in receive thread");
		pl.warn("mobile::ClientThread::run()::I'm in receive thread");
		pl.fatal("mobile::ClientThread::run()::I'm in receive thread");
		pl.error("mobile::ClientThread::run()::I'm in receive thread");
		pl.trace("mobile::ClientThread::run()::I'm in receive thread");
		try
		{
		    //Socket socket = new Socket("192.168.0.127",9999);
			Socket socket = new Socket("localhost",9999);
			outputport = new PrintStream(socket.getOutputStream());
			System.out.println("mobile::ClientThread::run()::Sending User --> "+Username);
			pl.info("mobile::ClientThread::run()::Sending User --> "+Username);
			pl.debug("mobile::ClientThread::run()::Sending User --> "+Username);
			pl.warn("mobile::ClientThread::run()::Sending User --> "+Username);
			pl.fatal("mobile::ClientThread::run()::Sending User --> "+Username);
			pl.error("mobile::ClientThread::run()::Sending User --> "+Username);
			pl.trace("mobile::ClientThread::run()::Sending User --> "+Username);
			System.out.println("mobile::ClientThread::run()::Sending Message --> "+Request);
			pl.info("mobile::ClientThread::run()::Sending Message --> "+Request);
			pl.debug("mobile::ClientThread::run()::Sending Message --> "+Request);
			pl.warn("mobile::ClientThread::run()::Sending Message --> "+Request);
			pl.fatal("mobile::ClientThread::run()::Sending Message --> "+Request);
			pl.error("mobile::ClientThread::run()::Sending Message --> "+Request);
			pl.trace("mobile::ClientThread::run()::Sending Message --> "+Request);
			outputport.println(Username);
			outputport.flush();
			outputport.println(Request);
			outputport.flush();
			inputPort = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String input = inputPort.readLine();
			System.out.println("mobile::ClientThread::run()::Reply Message --> "+input);
			pl.info("mobile::ClientThread::run()::Reply Message --> "+input);
			pl.debug("mobile::ClientThread::run()::Reply Message --> "+input);
			pl.warn("mobile::ClientThread::run()::Reply Message --> "+input);
			pl.fatal("mobile::ClientThread::run()::Reply Message --> "+input);
			pl.error("mobile::ClientThread::run()::Reply Message --> "+input);
			pl.trace("mobile::ClientThread::run()::Reply Message --> "+input);
		}	
		catch(Exception e)
		{
			System.out.println("mobile::ClientThread::run()::Unable to connect Server");
			pl.info("mobile::ClientThread::run()::Unable to connect Server");
			pl.debug("mobile::ClientThread::run()::Unable to connect Server");
			pl.warn("mobile::ClientThread::run()::Unable to connect Server");
			pl.fatal("mobile::ClientThread::run()::Unable to connect Server");
			pl.error("mobile::ClientThread::run()::Unable to connect Server");
			pl.trace("mobile::ClientThread::run()::Unable to connect Server");
			e.printStackTrace();
			pl.info(e.getMessage());
			pl.debug(e.getMessage());
			pl.warn(e.getMessage());
			pl.fatal(e.getMessage());
			pl.error(e.getMessage());
			pl.trace(e.getMessage());
		}
	}
		
}
